package com.umiwe.permission.service.impl;

import com.dingtalk.api.response.OapiUserListbypageResponse;


import com.umiwe.entity.UmiweUser;
import com.umiwe.entity.UmiweUserVO;
import com.umiwe.permission.mapper.UserMapper;
import com.umiwe.permission.service.DingDingService;
import com.umiwe.permission.service.UserService;
import com.umiwe.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private DingDingService dingDingService;

    @Resource
    private UserMapper userMapper;


    /**
     * 获取部门用户详情 从钉钉获取用户 新增数据
     * @param departmentId  部门id
     * @param offset
     * @param size
     * @return
     */
    @Override
    @Transactional
    public boolean addUser(Integer departmentId,Long offset,Long size) {
        OapiUserListbypageResponse oapiUserListbypageResponse = dingDingService.oapiUserListbypageRequest(DingDingUrlUtils.USER_LISTBYPAGE.value(),departmentId,offset,size);
        if(oapiUserListbypageResponse.getUserlist().size() > 0){
            //按部门查询 数据库里面的值 识别离职的员工
            ArrayList<UmiweUser> userDepartmentList = userMapper.getUserDepartmentList(departmentId);
            for(int i = 0;i<oapiUserListbypageResponse.getUserlist().size();i++){
                UmiweUser umiweUser = new UmiweUser();
                Map map = this.splitStringBuffer(oapiUserListbypageResponse.getUserlist().get(i).getName());
                if(!StringUtils.isEmpty((String)map.get("userName"))){
                    umiweUser.setUserName((String)map.get("userName"));
                }else{
                    Map<String, String> stringStringMap = dingDingService.userGet(oapiUserListbypageResponse.getUserlist().get(i).getUserid()); // 添加手机号进去
                    umiweUser.setUserName(stringStringMap.get("mobile"));
                }
                umiweUser.setDepartmentId(departmentId); //部门id
                umiweUser.setUserStatus(1);  //1=正常 2=锁定 3=离职
                umiweUser.setIsDelete(2); //1删除 2正常
                umiweUser.setDingtalkId(oapiUserListbypageResponse.getUserlist().get(i).getUserid()); //钉获取到的 用户id
                umiweUser.setChinaUserName((String)map.get("name")); //钉钉用户名称
                umiweUser.setUnionid(oapiUserListbypageResponse.getUserlist().get(i).getUnionid());
                if(userDepartmentList.size() > 0){
                    for(UmiweUser uu: userDepartmentList){
                        //修改操作
                        if(uu.getDingtalkId().equals(oapiUserListbypageResponse.getUserlist().get(i).getUserid())){
                            userMapper.updateDate(umiweUser);
                            userDepartmentList.remove(uu); //删除元素
                            break;
                        }
                    }
                }
                //查询数据是否存在
                if(!userMapper.getUserDingTalkId(oapiUserListbypageResponse.getUserlist().get(i).getUserid()))
                    userMapper.addUser(umiweUser);
                   /* String password = md5Utils.getEncryptedPwd("admin123456"); //初始化密码
                    umiweUser.setPassword(password);*/
            }
            //for循环执行完成之后
            if(userDepartmentList.size() > 0){
                for(UmiweUser user: userDepartmentList){
                    //做离职的人修改
                    userMapper.deleteDate(user.getDingtalkId());
                }
            }
            ++offset;
        }
        // 还有数据 继续加载
        if(oapiUserListbypageResponse.getHasMore() == true)
            this.addUser(departmentId,offset,size);
        return false;
    }


    public Map splitStringBuffer(String value){
        Map map = new HashMap();
        StringBuffer sb1 = new StringBuffer();
        StringBuffer sb2 = new StringBuffer();
        for(int j = 0;j<value.length();j++){
            char c = value.charAt(j);
            if((c<='z'&&c>='a')||(c<='Z'&&c>='A')){
                sb1.append(c); //英文
            }else{
                sb2.append(c); //中文
            }
        }
        map.put("userName",sb1.toString());
        map.put("name",sb2.toString());
        return map;
    }

    @Override
    @Transactional
    public Result getUserId(String code) {
        Map<String, String> map = dingDingService.oapiSnsGetuserinfoBycodeRequest(code, DingDingUrlUtils.SNS_GETUSERINFO_BY_CODE.value());
        String codes = map.get("code");
        if(codes.equals("0")){
            boolean addBoolean = userMapper.updateUserData(map.get("unionid"), map.get("openid"), map.get("userid"));
            if(addBoolean){
                //生成Token
                String userToken = JwtUtils.signToken(map.get("userName"), map.get("userid"));
                //userid 保存toekn
                redisUtil.set(map.get("userid"),userToken);
                //token 获取用户信息
                redisUtil.set(userToken,JsonUtils.objectToJson(userMapper.getDingTalkId(map.get("userid"))),2L, TimeUnit.HOURS);
                map.put("token",userToken);
                return Result.success(map);
            }
            return Result.error(ResultCode.DENGLU_FAIL);
        }
        return Result.fail(400,map.get("errmsg"));
    }

    @Override
    public Result login(String userId, String password) {
        UmiweUser user = userMapper.getDingTalkId(userId);
        if(Md5Utils.validPassword(password, user.getPassword()))
            return Result.success(true);
            return Result.error(ResultCode.LOGIN_FAIL);
    }

    /**
     * 修改密码
     * @return
     */
    @Override
    @Transactional
    public boolean updatePassWord(UmiweUserVO umiweUser) {
        UmiweUser user = userMapper.getDingTalkId(umiweUser.getDingtalkId());
        if(Md5Utils.validPassword(umiweUser.getPassword(), user.getPassword())){
            String password = Md5Utils.getEncryptedPwd(umiweUser.getNewPassword()); //识别成功 修改密码 初始化密码
            if(userMapper.updatePassWord(password, umiweUser.getDingtalkId()));
                //修改成功
                //修改失败
        }else{
            //原密码 输入错误
        }
        return false;
    }

    /**
     * 获取指定id的用户信息
     * @param id
     * @return
     */
    @Override
    public UmiweUser getUserById(Integer id) {
        return userMapper.getUserById(id);
    }

    /**
     * 获取所有的用户信息
     * @return
     */
    @Override
    public Result userList() {
       return Result.success(userMapper.selectList(null));
    }
}
